<?php
use think\facade\Session;
use think\facade\Request;
use think\facade\Config;
use think\facade\Db;
/**
 * 微信自定义菜单把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
function wechat_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'sub_button', $root = 0)
{
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent           = &$refer[$parentId];
                    $parent[$child][] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 获取微信配置信息
 * @param string $shop_id 商户ID
 */
function wxapi($shop_id='',$type)
{
    if(empty($shop_id)){
        $shop_id = StoreId();
    }
    //读取商户信息
    $shopinfo = \app\common\model\Store::where('id',$shop_id)->cache('shop_info'.$shop_id,86400,'store'.$shop_id)->find();
    //读取微信信息
    $app = \app\common\model\Wechat::$type($shopinfo);
    return $app;
}

/**
 * 解析模板消息,返回字段列表
 * @param $data 模板消息内容
 * @return array
 */
function parse_wechat_template($data){
    //
    $content = explode('}}', $data);
    foreach ($content as $r){
        $field[] = substr($r, strlen("{{")+strpos($r, '{{'),(strlen($r) - strpos($r, '.DATA'))*(-1));
    }
    return array_filter($field);
}